#include <iostream>
#include <string.h>
using std::cout;
using std::endl;

class String{
public:
    String()
    :_pstr(new char[1]())
    {
        cout<<"String()" <<endl;
    }
    
    String(const char * pstr)
    :_pstr(new char[strlen(pstr)+1]())
    {
        strcpy(_pstr,pstr);
        cout << "String(const char* pstr)"<<endl;
    }

    String(const String & rhs)
    :_pstr(new char[strlen(rhs._pstr)+1])
    {
        strcpy(_pstr,rhs._pstr);
        cout << "String(const String & rhs)" <<endl;
    }

    String & operator=(const String & rhs){
        cout << "String & operator=" <<endl;
        if(this != &rhs){
            delete [] _pstr;
            _pstr = new char[strlen(rhs._pstr)+1]();
            strcpy(_pstr,rhs._pstr);
        }
        return *this;
    }
    bool empty() const{
        cout << "empty" <<endl;
        if(strlen(_pstr) == 0){
            return true;
        } 
        return false;
    }

    int size() const{
        return strlen(_pstr);
    }

    const char * c_str() const{
        cout << "c_str()" <<endl;
        char * p = new char[strlen(_pstr) + 1]();
        strcpy(p,_pstr);
        return p;
    }

    ~String(){
        if(_pstr){
            delete [] _pstr;
            _pstr = nullptr;
        }
        cout << "~String" <<endl;
    }

    String & append(String & rhs){
       char * newptr = new char[strlen(_pstr) + rhs.size() + 1]();
       sprintf(newptr,"%s%s",_pstr,rhs._pstr);
       delete [] _pstr;
       _pstr = newptr;
       cout <<"append(String & rhs)"<<endl;
       return *this;
    }
    String & append(const char * pstr){
       char * newptr = new char[strlen(_pstr) + strlen(pstr) + 1]();
       sprintf(newptr,"%s%s",_pstr,pstr);
       delete [] _pstr;
       _pstr = newptr;
       cout << "append(const char * pstr)" <<endl;
       return *this;
    }

    void print() const{
        cout << _pstr <<endl;
    }

private:
    char * _pstr;
};

void test(){
    String s1;
    String s2("hello");
    String s3(s2);
    String s4("world");
    String s5 = s4;
    s4.append("wwwww");
    s4.print();
    s5.append(s2);
    s5.print();
}

int main()
{
    

    test ();
    return 0;
}

